package com.stars.services.impl.system;

import com.stars.common.base.BaseConstant;
import com.stars.common.base.ResultMsg;
import com.stars.common.valid.MyException;
import com.stars.dao.mapper.system.SystemPerUserMapper;
import com.stars.entity.dto.system.SystemPerUserDTO;
import com.stars.entity.system.SystemPerUserEntity;
import com.stars.services.impl.BaseConfigServiceImpl;
import com.stars.services.system.SystemPerUserConfigServices;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 * @Title: 资源与用户关系 业务逻辑
 * @author dj
 * @date 2019-10-17 20:57:38
 * @version V1.0
 *
 */
@Service
public class SystemPerUserConfigServicesImpl  extends BaseConfigServiceImpl<SystemPerUserMapper , SystemPerUserEntity> implements SystemPerUserConfigServices {

    @Autowired
    private SystemPerUserMapper systemPerUserMapper;
    @Override
    public ResultMsg addPerUser(String ids, String userId) throws Exception {
        String[] idList = addPerList(ids, userId);
        for (String id : idList) {
            if(StringUtils.isNotBlank(id)){
                SystemPerUserEntity entity = new SystemPerUserEntity();
                entity.setPerId(id);
                entity.setUserId(userId);
                SystemPerUserDTO byRelation = systemPerUserMapper.findByRelation(entity);
                if (null != byRelation) {
                    continue;
                }
                systemPerUserMapper.insertSelective(entity);
            }
        }
        return ResultMsg.success();
    }

    @Override
    public ResultMsg delPerUser(String ids, String userId) throws Exception {
        String[] idArray = addPerList(ids, userId);
        for (String id : idArray) {
            SystemPerUserEntity systemPermissionRelation = new SystemPerUserEntity();
            systemPermissionRelation.setPerId(id);
            systemPermissionRelation.setUserId(userId);
            systemPerUserMapper.deleteByRoleIdAndPerId(systemPermissionRelation);
        }
        return ResultMsg.success();
    }

    private String [] addPerList(String ids,String userId){
        if(StringUtils.isBlank(ids)){
            throw  new MyException("没有添加菜单资源");
        }
        if(StringUtils.isBlank(userId)){
            throw  new MyException("没有选择用户");
        }
        return ids.split(BaseConstant.SPOT);
    }
}